﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using nextwaver.SelfLearning.Model;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Management;
using System.Net.NetworkInformation;

namespace nextwaver.SelfLearning.Controls
{
    public partial class Logon : Form
    {
        public Logon()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll", EntryPoint = "HideCaret")]
        public static extern long HideCaret(IntPtr hwnd);

        #region Fields
        private string userID = ""; //--uesr id to log in into program and show in textbox--//
        ConnectServer.cConection Conn = new ConnectServer.cConection();
        #endregion

        private void init()
        {
            //write version info.
            label1.Text = "Version " + Application.ProductVersion + "\r\nProduct by Nextwaver.net " + "Co.,Ltd.";
            HideCaret(txtMain.Handle);
        }

        private void CalcBookTime(string TicketID)
        {
            try
            {
                //query balance time
                string sqlBalance = @"SELECT BalanceTime FROM [dbo].Fact_LearningTicket WHERE TicketID=@Ticket";
                sqlBalance = sqlBalance.Replace("@Ticket", VDOStatus.TicketID);
                DataSet ds = Conn.Retreive(sqlBalance, Conn.Conn);
                int balance = Model.Leaning.strTime2Int(ds.Tables[0].Rows[0][0].ToString());


                int time = Leaning.TimeToValue(Model.Leaning.GetServerTime());
                //query round
                string thisRound = @"EXECUTE [dbo].[FindRoundLearnning] '@TicketID',@ThisTimevalue";
                thisRound = thisRound.Replace("@TicketID", VDOStatus.TicketID);
                thisRound = thisRound.Replace("@ThisTimevalue", time.ToString());
                DataSet ds2 = Conn.Retreive(thisRound, Conn.Conn);
                if (ds2 != null && (ds2.Tables[0].Rows.Count > 0))
                {
                    string aRound = ds2.Tables[0].Rows[0][0].ToString();
                    VDOStatus.RoundLogin = aRound;



                    //query book time
                    string sqlBook = @"SELECT 30*(MAX(TimeId)-MIN(TimeId)+1) FROM [dbo].Booking
                    WHERE TicketID = @ticket
                    AND [Round]= @around
                    AND [Day] = DAY(GETDATE())
                    AND [Month]=MONTH(GETDATE())
                    AND [Year]= YEAR(GETDATE())
                    AND [Admission_Time] IS NULL";
                    sqlBook = sqlBook.Replace("@ticket", VDOStatus.TicketID);
                    sqlBook = sqlBook.Replace("@around", aRound);
                    DataSet ds1 = Conn.Retreive(sqlBook, Conn.Conn);
                    int book = 0;
                    //check value of book time, if user already logon set book=0, if not calc it. 
                    try
                    {
                        book = Convert.ToInt32(ds1.Tables[0].Rows[0][0]);
                    }
                    catch
                    {
                        book = 0;
                    }
                    int remain = balance - book;
                    string strRemain = Model.Leaning.Int2Time(remain);

                    string sqlUpdBalance = @"UPDATE [dbo].[Fact_LearningTicket]
                            SET [dbo].[Fact_LearningTicket].BalanceTime = '@BalaceTime'
                            WHERE [dbo].[Fact_LearningTicket].TicketID = '@Ticket'";
                    sqlUpdBalance = sqlUpdBalance.Replace("@BalaceTime", strRemain);
                    sqlUpdBalance = sqlUpdBalance.Replace("@Ticket", VDOStatus.TicketID);
                    Conn.Execute(sqlUpdBalance, Conn.Conn);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Application Error. Please contact system administrator.");
            }

        }

        private void SetAdmission4Booking(string SetAdmission4Booking_TicketID)
        {
            try
            {
                int time = Leaning.TimeToValue(Model.Leaning.GetServerTime());
                string setBookSQL = @"UPDATE [dbo].[Booking]
                SET Admission_Time = PARSENAME(REPLACE(convert(varchar(50),getdate(),108), ':', '.'), 3) +':'+PARSENAME(REPLACE(convert(varchar(50),getdate(),108), ':', '.'), 2) +' น.'
                WHERE TicketID = @TicketID
                AND [dbo].[Booking].[Month]=MONTH(GETDATE())
                AND [dbo].[Booking].[Day] = DAY(GETDATE())
                AND [dbo].[Booking].[Year] = YEAR(GETDATE())
                AND [Round] = @Round";
                setBookSQL = setBookSQL.Replace("@TicketID", SetAdmission4Booking_TicketID);
                setBookSQL = setBookSQL.Replace("@ThisTimevalue", time.ToString());
                setBookSQL = setBookSQL.Replace("@Round", VDOStatus.RoundLogin);

                Conn.Execute(setBookSQL, Conn.Conn);
            }
            catch (Exception ex)
            {
                //
            }
        }

        private void Logon_Load(object sender, EventArgs e)
        {
            init();

            string strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            ipAddress = addr[0];
        }

        #region Button
        private void panel1_Click(object sender, EventArgs e)//1
        {
            userID = txtMain.Text;
            userID += "1";
            SetValue(txtMain, userID);
        }

        private void panel2_Click(object sender, EventArgs e)//2
        {
            userID = txtMain.Text;
            userID += "2";
            SetValue(txtMain, userID);
        }

        private void panel3_Click(object sender, EventArgs e)//3
        {
            userID = txtMain.Text;
            userID += "3";
            SetValue(txtMain, userID);
        }

        private void panel5_Click(object sender, EventArgs e)//4
        {
            userID = txtMain.Text;
            userID += "4";
            SetValue(txtMain, userID);
        }

        private void panel6_Click(object sender, EventArgs e)//5
        {
            userID = txtMain.Text;
            userID += "5";
            SetValue(txtMain, userID);
        }

        private void panel7_Click(object sender, EventArgs e)//6
        {
            userID = txtMain.Text;
            userID += "6";
            SetValue(txtMain, userID);
        }

        private void panel9_Click(object sender, EventArgs e)//7
        {
            userID = txtMain.Text+"7";
            //userID += "7";
            SetValue(txtMain, userID);
        }

        private void panel10_Click(object sender, EventArgs e)//8
        {
            userID = txtMain.Text + "8";
            SetValue(txtMain, userID);
        }

        private void panel11_Click(object sender, EventArgs e)//9
        {
            userID = txtMain.Text + "9";
            SetValue(txtMain, userID);
        }

        private void panel13_Click(object sender, EventArgs e)//0
        {
            userID += "0";
            SetValue(txtMain, userID);
        }
        #endregion

        private void SetValue(RichTextBox txtBox,string value)
        {
            //HideCaret(txtMain.Handle);
            txtBox.Clear();
            txtBox.Text = value;
            HideCaret(txtMain.Handle);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool hasRight = false;
        string lateTime = "";
        string postLogin = "";
        private void panel12_Click(object sender, EventArgs e)
        {
            try
            {
                string sql = "SELECT * FROM [dbo].[DataSetting] WHERE DataSettingName ='LATE_TIME'";
                DataSet dss = Conn.Retreive(sql,Conn.Conn);
                lateTime = dss.Tables[0].Rows[0]["Value"].ToString();
            }
            catch (Exception ex)
            {
                lateTime = "15";
            }

            try
            {
                string sql0 = "SELECT * FROM [dbo].[DataSetting] WHERE DataSettingName ='MINS_LOGON_BEFORE'";
                DataSet dss0 = Conn.Retreive(sql0, Conn.Conn);
                postLogin = dss0.Tables[0].Rows[0]["Value"].ToString();
            }
            catch (Exception ex)
            {
                postLogin = "30";
            }

            try
            {
                string sqlCheckUseing = @"SELECT StateTicket FROM Fact_LearningTicket WHERE TicketID = '@tickrt'";
                sqlCheckUseing = sqlCheckUseing.Replace("@tickrt", userID);
                DataSet ds11 = Conn.Retreive(sqlCheckUseing, Conn.Conn);
                if (ds11 != null && (ds11.Tables[0].Rows.Count > 0))
                {
                    if (ds11.Tables[0].Rows[0]["StateTicket"].ToString() == "Using")
                    {
                        CommonLibrary.MessageBoxDialog(CommonLibrary.DialogType.Duplicate);
                    }
                    else
                    {
                        #region LOGIN
                        string sqlLogin = @"EXECUTE [dbo].[MemberLogin] @L0gTime,@Ticket,@minLate,@LoginBefor,@BranchID";
                        sqlLogin = sqlLogin.Replace("@L0gTime", "" + Model.Leaning.TimeToValue(Model.Leaning.GetServerTime()));
                        //sqlLogin = sqlLogin.Replace("@L0gTime", "1380");
                        sqlLogin = sqlLogin.Replace("@Ticket", userID);
                        sqlLogin = sqlLogin.Replace("@minLate", lateTime);
                        sqlLogin = sqlLogin.Replace("@LoginBefor", postLogin);
                        sqlLogin = sqlLogin.Replace("@BranchID", Config.Configurations.BranchID);
                        DataSet ds = Conn.Retreive(sqlLogin, Conn.Conn);
                        if (ds != null && (ds.Tables[0].Rows.Count > 0))
                        {
                            //VDOStatus.TicketID = pass;
                            ////ตัดเวลาจอง
                            //CalcBookTime(userID);
                            ////
                            ////Set Admisssion time for booking
                            ////
                            //SetAdmission4Booking(userID);

                            //frm_Course frm = new frm_Course(); //***************************************************************************************
                            ////Assign value to ticket ID
                            //ticketID = ds.Tables[0].Rows[0][0].ToString();
                            //frm.TicketID = ticketID;
                            //frm.StudentName = ds.Tables[0].Rows[0][1].ToString();
                            //frm.IpAddr = SELF.Model.Leaning.GetIP();
                            //frm.ShowDialog();
                            //display = "";
                            //txtMain.Text = "";
                            //pass = "";
                            VDOStatus.TicketID = userID;
                            VDOStatus.MemberName = ds.Tables[0].Rows[0][1].ToString();
                            hasRight = true;
                        }
                        else
                        {
                            CommonLibrary.MessageBoxDialog(CommonLibrary.DialogType.Error);
                        }
                        #endregion Login
                    }

                    //if end of reserv, exit code here.
                    //
                    //Thread thGetExit = new Thread(new ThreadStart(GetExit));
                    //thGetExit.Start();
                    //
                    //
                }
                else
                {
                    CommonLibrary.MessageBoxDialog(CommonLibrary.DialogType.Error);
                }
            }
            catch { }


            if (hasRight)
            {
                hasRight = false;
                MainMenu menu = new MainMenu();
                menu.Show();
            }
        }

        private string SpacialChar(int code)
        {
            System.Text.Encoding Encoder = System.Text.ASCIIEncoding.Default;
            Byte[] buffer = new byte[] { (byte)code };
            string spChar = Encoding.GetEncoding(1252).GetString(buffer);
            return spChar;
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            if ((txtMain.Text.Length > 0) && (userID.Length > 0))
            {
                userID = userID.Substring(0, userID.Length - 1);
                SetValue(txtMain, userID);
            }
        }

        private void panel8_Click(object sender, EventArgs e)
        {
            userID = "";
            SetValue(txtMain, userID);
        }

        int clickCount = 0;

        private void btTicker_DoubleClick(object sender, EventArgs e)
        {
            clickCount += 1;
            if (clickCount == 5)
            {
                panel15.Visible = true;
            }
        }

        private void txtMain_TextChanged(object sender, EventArgs e)
        {
            userID = txtMain.Text;
        }

        public void shutDown(ShutDown flag)
        {
            ManagementBaseObject outParam = null;
            ManagementClass sysOS = new ManagementClass("Win32_OperatingSystem");
            sysOS.Get();
            // enables required security privilege.
            sysOS.Scope.Options.EnablePrivileges = true;
            // get our in parameters
            ManagementBaseObject inParams = sysOS.GetMethodParameters("Win32Shutdown");
            // pass the flag of 0 = System Shutdown
            inParams["Flags"] = flag;
            inParams["Reserved"] = "0";
            foreach (ManagementObject manObj in sysOS.GetInstances())
            {
                outParam = manObj.InvokeMethod("Win32Shutdown", inParams, null);
            }
        }

        public enum ShutDown
        {
            LogOff = 0,
            Shutdown = 1,
            Reboot = 2,
            ForcedLogOff = 4,
            ForcedShutdown = 5,
            ForcedReboot = 6,
            PowerOff = 8,
            ForcedPowerOff = 12
        }

        Thread trlisten;
        IPAddress ipAddress;

        private void ListenToServer()
        {
            bool LISTENING = false;
            IPAddress localhostAddress = ipAddress;
            int port = 63000;
            //' PORT ADDRESS
            ///'''''''' making socket tcpList ''''''''''''''''
            TcpListener tcpList = new TcpListener(localhostAddress, port);
            try
            {
                tcpList.Start();
                LISTENING = true;

                while (LISTENING)
                {
                    while (tcpList.Pending() == false & LISTENING == true)
                    {
                        // Yield the CPU for a while.
                        Thread.Sleep(10);
                    }
                    if (!LISTENING)
                        break; // TODO: might not be correct. Was : Exit Do

                    TcpClient tcpCli = tcpList.AcceptTcpClient();
                    //ListBox1.Items.Add("Data from " & "128.10.20.63")
                    NetworkStream ns = tcpCli.GetStream();
                    StreamReader sr = new StreamReader(ns);
                    ///'''''' get data from client '''''''''''''''
                    string receivedData = sr.ReadLine();
                    if (receivedData == "###SHUTDOWN###")
                    {
                        shutDown(ShutDown.ForcedShutdown);
                    }
                    else

                        if (receivedData == "###REBOOT###")
                        {
                            shutDown(ShutDown.ForcedReboot);
                        }
                        else
                            if (receivedData == "###LOGOFF###")
                            {
                                shutDown(ShutDown.ForcedLogOff);
                            }
                            else
                            {   
                                //MessageBox.Show(receivedData);
                                this.Invoke((MethodInvoker)delegate
                                {
                                    MessageBox.Show(receivedData);
                                });
                            }

                    string returnedData = "###OK###";
                    //& " From Server"
                    StreamWriter sw = new StreamWriter(ns);
                    sw.WriteLine(returnedData);
                    sw.Flush();
                    sr.Close();
                    sw.Close();
                    ns.Close();
                    tcpCli.Close();
                }
                tcpList.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //error
                LISTENING = false;
            }
        }


 

    }
}
